<?php
namespace Admin\Controller;
use Think\Controller;
use Think\Page;
/**
* 超级管理员 索引 控制器
*/
class IndexController extends Controller
{
	
	function __construct()
	{
		parent::__construct();

		 if(session('admin') == null)
		 	$this->error('登录超时，请重新登录', '/Home/Index/adminLogin');
	}


	public function index()
	{
		$user = M('users');
		$count = $user->where(array('status' => 1))->count();
		$page  = new Page($count, 15);
        $show  = $page->show();

        $list  = $user->where( array('status' => 1) )->limit($page->firstRow.','.$page->listRows)->select();

        $this->assign('list', $list);
        $this->assign('page', $show);
        $this->display();
	}
    public function wxaccount()
    {
        $wxuser = M('wxuser');

        $count  = $wxuser->count();

        $page   = new Page($count, 8);
         
        $show   = $page->show();
        $list   = $wxuser->limit($page->firstRow.','.$page->listRows)->select();
        $this->assign('page', $show);
        $this->assign('list', $list);

        $this->display();
    }

    public function generate_token()
    {
        $character = 'abcdefghijklmnopqrstuvwxyz';
        $length = strlen($character);
        $tokenStr = '';

        for ($i=0; $i < 6; $i++) {
            $tokenStr .= $character[rand(0,$length-1)];
        }

        return $tokenStr.time(); 
    }

    public function wxaccount_add()
    {
        $region = M('region');

        $provinceList = $region->where(array('parentid'=>1, 'regiontype'=>1))->field('id, regionname')->select();
        if(IS_POST)
        {
            $wx = M('wxuser');
            $_POST['token'] =  $this->generate_token();
            $_POST['createtime'] = time();

            $img = $this->upload();

            if( $img )
            {
               $_POST['headerpic'] = '/'.$img;
            }

            if( $wx->add($_POST) )
            {
                $this->success('创建公众号成功', '/Admin/Index/wxaccount');
            }
            else
            {
                $this->error('创建公众号失败');
            }
    
        }
        
        $this->assign('token', $_POST['token']);
        $this->assign('provinceList', $provinceList);
        $this->display();

    }

    public function wxaccount_edit()
    {
        $id = isset($_GET['id'])?$_GET['id'] : 0;

        $wx = M('wxuser');
        $region = M('region');

        $wxaccount = $wx->where(array('id'=>$id))->find();
         
        $provinceList = $region->where(array('parentid'=>1, 'regiontype'=>1))->field('id, regionname')->select(); 

        $cityItem = $region->where(array('id'=>$wxaccount['city']))->field('id, regionname')->find(); 
        
        if(IS_POST)
        {
            $img = $this->upload();
            if( $img )
            {
                $_POST['headerpic'] = '/'.$img;
            }

            $_POST['updatetime'] = time();

            if( $wx->where(array('id'=>$id))->save($_POST) )
            {
                $this->success('保存成功');
            }
            else
            {
                $this->error('保存失败');
            }
        }

        $this->assign('wxItem', $wxaccount);
        $this->assign('provinceList', $provinceList);
        $this->assign('cityItem', $cityItem);
        $this->display();

    }

    public function getCity()
    {
        $provinceId = isset($_GET['parentid'])? $_GET['parentid'] : 0;

        if($provinceId != 0)
        {
            $region   = M('region');
            $cityList = $region->where(array('parentid'=>$provinceId))->select();
        
            $this->ajaxReturn($cityList);
        }

        $this->ajaxReturn("error");
    }

    public function wxaccount_delete()
    {
        $wxId = isset($_GET['id'])?$_GET['id']:0;
        $wx = M('wxuser');

        if($wx->where(array('id'=>$wxId))->delete() )
        {
            $this->success('删除成功');
        }
        else
            $this->error('删除失败');
    }
    
	public function admin_info()
	{
         $admin = M('admin');
         $info  = $admin->where(array('id'=>session('admin')))->find();
        if(IS_POST)
        {
           
            $admin->username = $_POST['username'];
            $admin->telephone = $_POST['telephone'];

            if( $admin->where(array('id' => session('admin')))->save() )
            {
                $this->success('操作成功');
            }
            else
            {
                $this->error('操作失败');
            }

        }
        
        $this->assign('admin', $info);
        $this->display();
	}

    public function passwordEdit()
    {
        if(IS_POST)
        {
            $cusPassword = M('admin')->where(array('id' => session('admin')))->field('password')->find();
            if(trim($cusPassword['password']) === md5(trim($_POST['pwd'])))
            {
                //TODO:过滤特殊字符
                if(trim($_POST['new_pwd1']) === trim($_POST['new_pwd2']))
                {
                    //$this->user->password = md5(trim($_POST['new_pwd1']));
                    $admin = M('admin');
                    $admin->password = md5(trim($_POST['new_pwd1']));
                    if($admin->where(array('id' => session('admin')))->save())
                    {
                        $this->success('密码修改成功');
                    }
                    else
                    {
                        $this->error('密码修改失败');
                    }
                }
                else
                {
                    $this->error('新密码输入不一致');
                }

            }
            else
            {
                $this->error('原密码输入错误');
            }

        }
    } 

    public function user_add()
    {
        $wxuser = M('wxuser')->field('id, wxname')->select();
        if(IS_POST)
        {
            $cusUser = M('users')->where(array('email'=>$_POST['email']))->find();
            
            if( $cusUser )
            {
                header("Content-type: text/html; charset=utf-8");
                die('该用户已存在');
            }
            if( $_POST['email'] != '' && $_POST['pwd'] != '' && $_POST['pwd'] === $_POST['pwd_rep'])
            {
                $user = M('users');

                $user->email       = $_POST['email'];
                $user->username    = $_POST['username'];
                $user->mp          = $_POST['mp'];
                $user->password    = md5(trim($_POST['pwd']));
                $user->wx_id       = $_POST['wx_id'];
                $user->createtime  = time();
                $user->lasttime    = time();
                $user->status      = 1;
                $user->createip    = htmlspecialchars(trim(get_client_ip()));
                $user->lastip      = htmlspecialchars(trim(get_client_ip()));

                if($user->add())
                {
                    $this->success('创建用户成功');
                }
                else
                    $this->error('创建用户失败');
            }
            else
            {
                $this->error('用户名密码不为空或密码输入不一致');
            }
        }
        $this->assign('wxuser', $wxuser);
        $this->display();

    }

    public function user_delete()
    {
        $userId = isset($_GET['id'])?$_GET['id']:0;
        $user = M('users');

        if($user->where(array('id'=>$userId))->delete() )
        {
            $this->success('删除成功');
        }
        else
            $this->error('删除失败');

    }

    public function user_edit()
    {
        $userId = isset($_GET['id'])?$_GET['id']:0; 
        
        $user   = M('users')->where(array('id' => $userId))->find(); 
        $cus_wx = M('wxuser')->where(array('id'=> $user['wx_id']))->field('id')->find();
        $wxuser = M('wxuser')->field('id,wxname')->select();

        if(IS_POST)
        {
        
            if( M('users')->where(array('id'=>$userId))->save($_POST) )
            {
                $this->success('保存成功');
            }
            else
                $this->error('保存失败');
        }

        $this->assign('user', $user);
        $this->assign('wxuser',$wxuser);
        $this->assign('cus_wx',$cus_wx);
        $this->display();
    }


    public function user_auth()
    {
        if($_GET['id'])
        {
           $access = M('auth_group_access');
           $groupList  = M('auth_group')->where(array('status'=>1) )->field('id, title')->select();
           $userId  =  $_GET['id'];
           $accessItem = $access->where(array('uid' => $userId) )->find();
           $method  =  'save';
           if(!$accessItem)
           {
               $method='add';
           }
           if(IS_POST)
           {
                if($method == 'add')
                {
                    $_POST['uid'] = $userId;
                    if( $access->$method($_POST) )
                    {
                        $this->success('保存成功');
                    }
                    else
                    {
                        $this->error('保存失败');
                    }
                }
                else
                {
                    if($access->where(array('uid'=>$userId))->$method($_POST))
                   {
                       $this->success('保存成功');
                   }
                   else
                   {
                       $this->error('保存失败');
                   }
                }
               

           }
           
           $this->assign('accessItem', $accessItem);
           $this->assign('groupList',  $groupList);

           $this->display();
        }
        else
        {
            $this->error('非法操作');
        }
    }
	


	public function logout()
	{
        session(null);
        session_destroy();
        unset($_SESSION);
        redirect('/Home/Index/adminLogin');
	}


    private function upload(){
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Public/Uploads/wxheader/'; // 设置附件上传根目录
        $upload->subName   =    array( "date", "Ymd" );
        $upload->saveName  =    array( "uniqid", "wxheader" );
        // 上传文件
        $info   =   $upload->upload();
        $img = "";
        //if(!$info) {// 上传错误提示错误信息
            //$this->error($upload->getError());
        //}else{// 上传成功
        if( $info ){
             //$file =
            //$this->ajaxReturn( $info );
            //$temq =   explode( "./", $file['savepath'], 2 );
            foreach($info as $file){
                $img = "Public/Uploads/wxheader/" . date('Ymd') . "/" . $file['savename'];
            }
        }else{
             //$this->ajaxReturn( $upload->getError() );
        }
            //$this->success('上传成功！');
        //}
        return $img;
    }


}
?>
